import { userList, userCount } from "@/request/api";

interface StateUser {
    userlist: Array<object>,
    pageSize: number,
    pageNum: number,
    count: number
}

const state = {
    userlist: [],
    //pageSize页面显示条数
    pageSize: 3,
    //页码
    pageNum: 1,
    //总条数
    count: 0
}

const getters = {
    getUser(state: StateUser) {
        return state.userlist
    },
    getSize(state: StateUser) {
        return state.pageSize
    },
    getCount(state: StateUser) {
        return state.count
    }
}

const mutations = {
    REQ_USERLIST(state: StateUser, payload: any) {
        state.userlist = payload
    },
    REQ_COUNT(state: StateUser, payload: any) {
        state.count = payload
    },
    //同步修改页码事件
    REQ_PAGE(state: StateUser, payload: any) {
        state.pageNum = payload
    }
}

const actions = {
    getUserListActions(context: any) {
        userList({
            size: context.state.pageSize,
            page: context.state.pageNum
        }).then(res => {
            console.log(res, '管理员列表行动');
            if (res.code == 200) {
                let list:any = res.list ? res.list : []
                if (context.state.pageNum != 1 && list.length == 0) {
                    //给pageNum -1 并重新调用列表
                    context.dispatch('changePageAction', context.state.pageNum - 1)
                }
                context.commit('REQ_USERLIST', list)
            }
        })
    },
    //获取总条数
    async getUserCount(context: any) {
        let res:any = await userCount()
        // console.log(res, '总条数');
        context.commit('REQ_COUNT', res.list[0].total)
    },
    //获取当前页行动并重新调用列表行动
    changePageAction(context: any, payload: any) {
        //修改页码
        context.commit('REQ_PAGE', payload)
        //重新调用接口 dispatch触发actions  commit提交mutations
        context.dispatch('getUserListActions')
    }
}

export default {
    state,
    getters,
    mutations,
    actions,
    namespaced: true
}